package com.evan.review.architecture.components;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.ExistingWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import com.evan.review.R;
import com.evan.review.architecture.components.workers.SimpleWorker;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * WorkManager示例Activity
 * 展示WorkManager的基本用法
 */
public class WorkManagerExampleActivity extends AppCompatActivity {
    
    private TextView tvStatus;
    private TextView tvResult;
    private Button btnOneTimeWork;
    private Button btnPeriodicWork;
    private Button btnConstrainedWork;
    private Button btnCancelWork;
    
    private UUID lastWorkId;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_example);
        
        // 设置标题
        setTitle("WorkManager示例");
        
        // 初始化视图
        initViews();
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tv_status);
        tvResult = findViewById(R.id.tv_result);
        
        // 一次性任务按钮
        btnOneTimeWork = findViewById(R.id.btn_one_time_work);
        btnOneTimeWork.setOnClickListener(v -> {
            scheduleOneTimeWork();
        });
        
        // 周期性任务按钮
        btnPeriodicWork = findViewById(R.id.btn_periodic_work);
        btnPeriodicWork.setOnClickListener(v -> {
            schedulePeriodicWork();
        });
        
        // 带约束的任务按钮
        btnConstrainedWork = findViewById(R.id.btn_constrained_work);
        btnConstrainedWork.setOnClickListener(v -> {
            scheduleConstrainedWork();
        });
        
        // 取消任务按钮
        btnCancelWork = findViewById(R.id.btn_cancel_work);
        btnCancelWork.setOnClickListener(v -> {
            cancelWork();
        });
    }
    
    /**
     * 调度一次性任务
     */
    private void scheduleOneTimeWork() {
        // 创建输入数据
        Data inputData = new Data.Builder()
                .putString("task_type", "一次性任务")
                .putLong("timestamp", System.currentTimeMillis())
                .build();
        
        // 创建一次性任务请求
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SimpleWorker.class)
                .setInputData(inputData)
                .addTag("one_time_work")
                .build();
        
        // 保存任务ID，用于后续取消
        lastWorkId = workRequest.getId();
        
        // 提交任务
        WorkManager.getInstance(this)
                .enqueueUniqueWork(
                        "one_time_work",
                        ExistingWorkPolicy.REPLACE,
                        workRequest);
        
        // 观察任务状态
        observeWorkStatus(workRequest.getId());
        
        // 更新UI
        tvStatus.setText("一次性任务已调度");
    }
    
    /**
     * 调度周期性任务
     */
    private void schedulePeriodicWork() {
        // 创建输入数据
        Data inputData = new Data.Builder()
                .putString("task_type", "周期性任务")
                .putLong("timestamp", System.currentTimeMillis())
                .build();
        
        // 创建周期性任务请求（最小间隔15分钟）
        PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(
                SimpleWorker.class, 15, TimeUnit.MINUTES)
                .setInputData(inputData)
                .addTag("periodic_work")
                .build();
        
        // 保存任务ID，用于后续取消
        lastWorkId = workRequest.getId();
        
        // 提交任务
        WorkManager.getInstance(this).enqueue(workRequest);
        
        // 观察任务状态
        observeWorkStatus(workRequest.getId());
        
        // 更新UI
        tvStatus.setText("周期性任务已调度（每15分钟执行一次）");
    }
    
    /**
     * 调度带约束的任务
     */
    private void scheduleConstrainedWork() {
        // 创建约束条件
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 需要网络连接
                .setRequiresCharging(true) // 需要充电状态
                .build();
        
        // 创建输入数据
        Data inputData = new Data.Builder()
                .putString("task_type", "带约束的任务")
                .putLong("timestamp", System.currentTimeMillis())
                .build();
        
        // 创建带约束的任务请求
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SimpleWorker.class)
                .setConstraints(constraints)
                .setInputData(inputData)
                .addTag("constrained_work")
                .build();
        
        // 保存任务ID，用于后续取消
        lastWorkId = workRequest.getId();
        
        // 提交任务
        WorkManager.getInstance(this).enqueue(workRequest);
        
        // 观察任务状态
        observeWorkStatus(workRequest.getId());
        
        // 更新UI
        tvStatus.setText("带约束的任务已调度（需要网络连接和充电状态）");
    }
    
    /**
     * 取消任务
     */
    private void cancelWork() {
        if (lastWorkId != null) {
            // 取消指定ID的任务
            WorkManager.getInstance(this).cancelWorkById(lastWorkId);
            tvStatus.setText("任务已取消（ID: " + lastWorkId + "）");
        } else {
            // 取消所有任务
            WorkManager.getInstance(this).cancelAllWork();
            tvStatus.setText("所有任务已取消");
        }
    }
    
    /**
     * 观察任务状态
     */
    private void observeWorkStatus(UUID workId) {
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(workId)
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        if (workInfo != null) {
                            // 更新状态
                            WorkInfo.State state = workInfo.getState();
                            tvStatus.setText("任务状态: " + state.name());
                            
                            // 如果任务成功完成，显示输出数据
                            if (state == WorkInfo.State.SUCCEEDED) {
                                Data outputData = workInfo.getOutputData();
                                String result = outputData.getString("result");
                                long completionTime = outputData.getLong("completion_time", 0);
                                
                                tvResult.setText("任务结果: " + result + "\n完成时间: " + completionTime);
                            }
                        }
                    }
                });
    }
} 